using System;
using System.IO.Ports;

class Receiver
{
    static SerialPort _serialPort;

    static void Main()
    {
        // 1. 配置串口参数（根据实际修改）
        _serialPort = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One)
        {
            Handshake = Handshake.None,
            ReadTimeout = 500
        };

        try
        {
            _serialPort.Open();
            Console.WriteLine("乙方已启动，等待接收数据...");

            // 2. 注册数据接收事件
            _serialPort.DataReceived += (sender, e) =>
            {
                try
                {
                    string receivedData = _serialPort.ReadLine();
                    string recvTimestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    Console.WriteLine($"[RECV {recvTimestamp}] {receivedData}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"接收错误: {ex.Message}");
                }
            };

            // 保持程序运行
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"错误: {ex.Message}");
        }
        finally
        {
            if (_serialPort.IsOpen) _serialPort.Close();
        }
    }
}